using Godot;
using System;

/// <summary>
/// 提供C#和GDScript之间的交互功能
/// </summary>
public partial class GDScriptBridge : Node
{
    // 单例实例
    private static GDScriptBridge _instance;
    
    // 信号定义，用于与GDScript通信
    [Signal]
    public delegate void CardPlayedEventHandler(Resource card);
    
    [Signal]
    public delegate void PlayerStatChangedEventHandler(Resource playerStats);
    
    /// <summary>
    /// 获取单例实例
    /// </summary>
    public static GDScriptBridge Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new GDScriptBridge();
            }
            return _instance;
        }
    }
    
    /// <summary>
    /// 初始化桥接器
    /// </summary>
    public override void _Ready()
    {
        _instance = this;
        
        // 连接到GDScript的信号
        ConnectToGDScriptSignals();
    }
    
    /// <summary>
    /// 连接到GDScript的信号
    /// </summary>
    private void ConnectToGDScriptSignals()
    {
        // 获取全局事件节点
        var events = GetNode("/root/Events");
        if (events != null)
        {
            // 先检查是否已连接，避免重复连接
            if (!events.IsConnected("card_played", new Callable(this, nameof(OnCardPlayed))))
            {
                // 连接GDScript信号到C#方法
                events.Connect("card_played", new Callable(this, nameof(OnCardPlayed)));
            }
            
            if (!events.IsConnected("player_hit", new Callable(this, nameof(OnPlayerHit))))
            {
                events.Connect("player_hit", new Callable(this, nameof(OnPlayerHit)));
            }
        }
    }
    
    /// <summary>
    /// 当卡牌被打出时调用
    /// </summary>
    /// <param name="card">被打出的卡牌</param>
    private void OnCardPlayed(Resource card)
    {
        // 处理来自GDScript的卡牌事件
        GD.Print("C# received card played event: " + card.Get("id").AsString());
        
        // 发出C#信号，供其他C#类使用
        EmitSignal(SignalName.CardPlayed, card);
    }
    
    /// <summary>
    /// 当玩家受到伤害时调用
    /// </summary>
    private void OnPlayerHit()
    {
        GD.Print("C# received player hit event");
        // 这里可以添加更多处理逻辑
    }
    
    /// <summary>
    /// 从C#调用GDScript函数
    /// </summary>
    /// <param name="nodePath">节点路径</param>
    /// <param name="method">方法名</param>
    /// <param name="args">参数数组</param>
    /// <returns>调用结果</returns>
    public Variant CallGDScriptMethod(string nodePath, string method, params Variant[] args)
    {
        var node = GetNodeOrNull(nodePath);
        if (node == null)
        {
            GD.PrintErr($"Node not found: {nodePath}");
            return new Variant();
        }
        
        return node.Call(method, args);
    }
} 